#include "Battery.h"
#include "USART_HMI.h"
#include "Controler.h"

static uint16_t Voltage = 0;
#define BUFFER_LENGTH 50
static uint16_t batteryVoltageBuffer[BUFFER_LENGTH]; // 电池电压缓存
static uint8_t batteryVoltageBufferIndex = 0;       // 电池电压缓存索引
const static uint16_t LowVoltage = 3650;
static uint8_t ProtectionFlag = 0;

void BatteryCheckCallback(void)
{
    uint32_t sum = 0;
    for (uint8_t i = 0; i < BUFFER_LENGTH; i++)
    {
        if (batteryVoltageBuffer[i] != 0)
        {
            sum += batteryVoltageBuffer[i];
        }

    }
    Voltage = sum /BUFFER_LENGTH;

    if (Voltage < LowVoltage)
    {
        if (ProtectionFlag == 0)
        {
            HMILowVoltage();
            ProtectionFlag = 1;
        }
    }
    else
    {
    	ProtectionFlag = 0;
    }
}

uint8_t BatteryGetProtection(void)
{
    return ProtectionFlag;
}

void BatteryADCValueSet(uint16_t adc)
{
    batteryVoltageBuffer[batteryVoltageBufferIndex++] = adc;
    batteryVoltageBufferIndex %= BUFFER_LENGTH;
}
